﻿using BZ.Logger;
using HalconDotNet;
using NDK.Module.Model;
using NDK.Motion.BLL;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static NDK.Module.Model.Common;

namespace NDK.Module.BLL
{
    public class EventVisoion
    {
        static List<string> BlockFileName = new List<string>() { "Min", "Mid", "Max" };
        public static List<DataItem> PosionRefresh(PosionImageRefreshEventArgs e)
        {
            List<DataItem> listDataItem = new List<DataItem>();
            VisionResult(e.FileName, e.outDataName, e.Imagesname, e.Images, ref listDataItem, e.SN, e.panNum, e.panNum1, (CurProType.Contains("Uncutting") ? 0 : 1));
            return listDataItem;
        }

        public static void PosionRefresh(PosionImageRefreshEventArgs e, ref List<DataItem> listDataItem, ref List<DataItem> listDataItem1, ref List<DataItem> listDataItem2)
        {
            VisionResult(e.FileName, e.outDataName, e.outDataName1, e.outDataName2, e.Imagesname, e.Images, ref listDataItem, ref listDataItem1, ref listDataItem2, e.SN, "1", (CurProType.Contains("Uncutting") ? 0 : 1));
        }

        /// <summary>
        /// 侧相机
        /// </summary>
        public static void OnLoadingCameraRefresh(ImageRefreshEventArgs e)
        {
            e.panNum = Machine.DicLocalData[e.SN].Position;
            Task task = Task.Run(new Action(() =>
            {
                string FileName = "SideCCDStation";
                if (whichBlock != -1)
                    FileName = $"{FileName}_{BlockFileName[whichBlock]}";
                List<DataItem> listDataItem = new List<DataItem>();
                VisionResult(FileName, "SideCCDData", new List<string>() { "侧CCD1", "侧CCD2", "侧CCD3" }, new List<HImage>() {
               Machine.DicLocalData[e.SN].SideCam_1, Machine.DicLocalData[e.SN].SideCam_2,  Machine.DicLocalData[e.SN].SideCam_3}, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                Machine.DicLocalData[e.SN].MeasureData.AddRange(listDataItem);
            }));
            Machine.DicLocalData[e.SN].tasks.Add(task);
        }

        /// <summary>
        /// 上激光
        /// </summary>
        public static void OnCarrierUpLaserRefresh(ImageRefreshEventArgs e)
        {
            e.panNum = Machine.DicLocalData[e.SN].Position;
            Task task = Task.Run(new Action(() =>
            {
                string FileName = "TopLaserStation";
                if (whichBlock != -1)
                    FileName = $"{FileName}_{BlockFileName[whichBlock]}";
                List<DataItem> listDataItem = new List<DataItem>();
                VisionResult(FileName, "TopLaserData", new List<string>() { "TopLaser" }, new List<HImage>() {
                Machine.DicLocalData[e.SN].UpLaser}, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                Machine.DicLocalData[e.SN].MeasureData.AddRange(listDataItem);
            }));
            Machine.DicLocalData[e.SN].tasks.Add(task);
        }

        /// <summary>
        /// 侧激光
        /// </summary>
        public static void OnCarrierTopLaserRefresh(ImageRefreshEventArgs e)
        {
           
            e.panNum = Machine.DicLocalData[e.SN].Position;
            Task task = Task.Run(new Action(() =>
            {
                string FileName = "TopCCDStation";
                if (whichBlock != -1)
                    FileName = $"{FileName}_{BlockFileName[whichBlock]}";
                List<DataItem> listDataItem = new List<DataItem>();
                if (ProjectName.Contains("4080"))
                {
                    VisionResult(FileName, "TopCCDData", new List<string>() { "Image1-1", "Image2-1","Image3-1","Image4-1","Image4-2", "Image1-3", "Image2-3", "Image4-3", "Image1-4", "Image4-4",
    "上CCD1", "上CCD2", "上CCD3", "上CCD4" }, new List<HImage>() {
Machine.DicLocalData[e.SN].SideLaser_短边1_1,Machine.DicLocalData[e.SN].SideLaser_短边2_1, Machine.DicLocalData[e.SN].SideLaser_短边3_1, Machine.DicLocalData[e.SN].SideLaser_短边4_1,Machine.DicLocalData[e.SN].SideLaser_短边4_2,
       Machine.DicLocalData[e.SN].SideLaser_长边1_3,Machine.DicLocalData[e.SN].SideLaser_长边2_3,
       Machine.DicLocalData[e.SN].SideLaser_长边4_3, Machine.DicLocalData[e.SN].SideLaser_长边1_4,Machine.DicLocalData[e.SN].SideLaser_长边4_4,
     Machine.DicLocalData[e.SN].UpCamImage_1, Machine.DicLocalData[e.SN].UpCamImage_2,Machine.DicLocalData[e.SN].UpCamImage_3, Machine.DicLocalData[e.SN].UpCamImage_4
 }, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                }
                else if (ProjectName.Contains("4081"))
                {
                    VisionResult(FileName, "TopCCDData", new List<string>() { "Image1-1", "Image2-1", "Image3-1", "Image4-1", "Image1-3", "Image2-3", "Image4-3",
     "Image1-4","上CCD1", "上CCD2", "上CCD3", "上CCD4" }, new List<HImage>() {
Machine.DicLocalData[e.SN].SideLaser_短边1_1,Machine.DicLocalData[e.SN].SideLaser_短边2_1, Machine.DicLocalData[e.SN].SideLaser_短边3_1, Machine.DicLocalData[e.SN].SideLaser_短边4_1,
       Machine.DicLocalData[e.SN].SideLaser_长边1_3,Machine.DicLocalData[e.SN].SideLaser_长边2_3,
       Machine.DicLocalData[e.SN].SideLaser_长边4_3, Machine.DicLocalData[e.SN].SideLaser_长边1_4,
     Machine.DicLocalData[e.SN].UpCamImage_1, Machine.DicLocalData[e.SN].UpCamImage_2,Machine.DicLocalData[e.SN].UpCamImage_3, Machine.DicLocalData[e.SN].UpCamImage_4
 }, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                }
                else if (ProjectName.Contains("4084"))
                {
                    VisionResult(FileName, "TopCCDData", new List<string>() { "Image1-1", "Image2-1","Image3-1","Image4-1","Image4-2", "Image1-3", "Image2-3", "Image4-3", "Image1-4", "Image4-4",
     "上CCD1", "上CCD2", "上CCD3", "上CCD4" }, new List<HImage>() {
 Machine.DicLocalData[e.SN].SideLaser_短边1_1,Machine.DicLocalData[e.SN].SideLaser_短边2_1, Machine.DicLocalData[e.SN].SideLaser_短边3_1, Machine.DicLocalData[e.SN].SideLaser_短边4_1,Machine.DicLocalData[e.SN].SideLaser_短边4_2,
        Machine.DicLocalData[e.SN].SideLaser_长边1_3,Machine.DicLocalData[e.SN].SideLaser_长边2_3,
        Machine.DicLocalData[e.SN].SideLaser_长边4_3, Machine.DicLocalData[e.SN].SideLaser_长边1_4,Machine.DicLocalData[e.SN].SideLaser_长边4_4,
      Machine.DicLocalData[e.SN].UpCamImage_1, Machine.DicLocalData[e.SN].UpCamImage_2,Machine.DicLocalData[e.SN].UpCamImage_3, Machine.DicLocalData[e.SN].UpCamImage_4
  }, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                }
                else if (ProjectName.Contains("4062"))
                {
                    VisionResult(FileName, "TopCCDData", new List<string>() { "Image1-1", "Image2-1", "Image3-1", "Image4-1", "Image3-2", "Image1-3", "Image2-3",
                    "Image3-3","Image4-4","Image3-4","上CCD1", "上CCD2" }, new List<HImage>() {
               Machine.DicLocalData[e.SN].SideLaser_短边1_1,Machine.DicLocalData[e.SN].SideLaser_短边2_1, Machine.DicLocalData[e.SN].SideLaser_短边3_1, Machine.DicLocalData[e.SN].SideLaser_短边4_1,
                         Machine.DicLocalData[e.SN].SideLaser_短边3_2,Machine.DicLocalData[e.SN].SideLaser_长边1_3,Machine.DicLocalData[e.SN].SideLaser_长边2_3,Machine.DicLocalData[e.SN].SideLaser_长边3_3,
                      Machine.DicLocalData[e.SN].SideLaser_长边4_4, Machine.DicLocalData[e.SN].SideLaser_长边3_4,
                    Machine.DicLocalData[e.SN].UpCamImage_1, Machine.DicLocalData[e.SN].UpCamImage_2
                }, ref listDataItem, e.SN, e.panNum, (CurProType.Contains("unCutting") ? 0 : 1));
                }
                    Machine.DicLocalData[e.SN].MeasureData.AddRange(listDataItem);
            }));
            Machine.DicLocalData[e.SN].tasks.Add(task);
        }

        /// <summary>
        /// 下激光
        /// </summary>
        public static void OnTransMoverLaserRefresh(ImageRefreshEventArgs e)
        {
            e.panNum = Machine.DicLocalData[e.SN].Position;
            Task task = Task.Run(new Action(() =>
            {
                string FileName = "Mid_DownLaserStation";
                if (whichBlock != -1)
                    FileName = $"{FileName}_{BlockFileName[whichBlock]}";
                List<DataItem> listDataItem = new List<DataItem>();
                VisionResult(FileName, "DownLaserData", new List<string>() { "DownLaser1", "DownLaser2", "MidLaser1" }, new List<HImage>() {
            Machine.DicLocalData[e.SN].DownLaser1, Machine.DicLocalData[e.SN].DownLaser2, Machine.DicLocalData[e.SN].MidLaser1},
            ref listDataItem, e.SN, e.panNum, (CurProType.Contains("Uncutting") ? 0 : 1));
                Machine.DicLocalData[e.SN].MeasureData.AddRange(listDataItem);
            }));
            Machine.DicLocalData[e.SN].tasks.Add(task);
        }

        /// <summary>
        /// 算法处理
        /// </summary>
        /// <param name="FileName">工站运行名称</param>
        /// <param name="outDataName">输出名称</param>
        /// <param name="inputImageName">图片名称</param>
        /// <param name="InputImage">图片</param>
        /// <param name="listDataItems">输出数据</param>
        /// <param name="inputID">键-二维码(唯一)</param>
        /// <param name="PanNum">通道</param>
        /// <returns></returns>
        public static bool VisionResult(string FileName, string outDataName, List<string> inputImageName, List<HImage> InputImage, ref List<DataItem> listDataItems, string inputID = "code", string PanNum = "1", string PanNum1 = "2", int Iscutting = 0)
        {
            try
            {
                string strResult = string.Empty;
                VisionPlatform.VisionManager.Engine eng = null;
                eng = new VisionPlatform.VisionManager.Engine(FileName);
                eng.SetInputNumber("PanNum", Convert.ToInt32(PanNum));
                eng.SetInputNumber("PanNum1", Convert.ToInt32(PanNum1));
                eng.SetInputNumber("isCutting", Iscutting);
                eng.SetInputString("ID", inputID);
                for (int i = 0; i < inputImageName.Count; i++)
                    eng.SetInputImage(inputImageName[i], InputImage[i]);
                eng.ActionFun();
                strResult = eng.GetOutputString(outDataName);
                if (strResult != "")
                {
                    //Dictionary<string, double> dic = new Dictionary<string, double>();
                    //dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);
                    int position = 0;
                    var s = strResult.Substring(1, strResult.Length - 1);
                    string[] str = s.Split(',');
                    for (int i = 0; i < str.Length; i++)
                    {
                        DataItem FAI = new DataItem
                        {
                            Value = double.Parse(str[i]),
                            Position = position
                        };
                        listDataItems.Add(FAI);
                    }
                }
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName} 算法处理报错:{ex}", LogType.Error);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 算法处理
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="outDataName">测量结果输出名称</param>
        /// <param name="inputImageName">图片名称</param>
        /// <param name="InputImage">图片</param>
        /// <param name="listDataItems">测量值</param>
        /// <param name="ID_SN">二维码</param>
        /// <param name="inputFixtureID">通道</param>
        /// <returns></returns>
        public static bool VisionResult(string FileName, string outDataName, List<string> inputImageName, List<HImage> InputImage, ref List<DataItem> listDataItems, string ID_SN = "Code", string inputFixtureID = "1", int Iscutting = 0)
        {
            try
            {
                string strResult = string.Empty;
                VisionPlatform.VisionManager.Engine eng = null;
                eng = new VisionPlatform.VisionManager.Engine(FileName);
                eng.SetInputNumber("PanNum", Convert.ToInt16(inputFixtureID));
                eng.SetInputNumber("isCutting", Iscutting);
                eng.SetInputString("ID", ID_SN);
                for (int i = 0; i < inputImageName.Count; i++)
                    eng.SetInputImage(inputImageName[i], InputImage[i]);
                eng.ActionFun();
                strResult = eng.GetOutputString(outDataName);
                if (strResult != "")
                {
                    Dictionary<string, double> dic = new Dictionary<string, double>();
                    dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);
                    int position = 0;

                    foreach (var item in dic)
                    {
                        string FAIName = item.Key;
                        string FAIValue = item.Value.ToString();
                        DataItem FAI = new DataItem
                        {
                            Name = FAIName,
                            Value = double.Parse(FAIValue),
                            Position = position
                        };
                        listDataItems.Add(FAI);
                    }
                }
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName} 算法处理报错:{ex}", LogType.Error);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 算法处理
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="outDataName">测量结果输出名称</param>
        /// <param name="inputImageName">图片名称</param>
        /// <param name="InputImage">图片</param>
        /// <param name="listDataItems">测量值</param>
        /// <param name="ID_SN">二维码</param>
        /// <param name="inputFixtureID">通道</param>
        /// <returns></returns>
        public static bool VisionResult(string FileName, string outDataName, string outDataName1, string outDataName2, List<string> inputImageName, List<HImage> InputImage, ref List<DataItem> listDataItems,
            ref List<DataItem> listDataItems1, ref List<DataItem> listDataItems2, string ID_SN = "Code", string inputFixtureID = "1", int Iscutting = 0)
        {
            try
            {
                string strResult = string.Empty;
                string strResult1 = string.Empty;
                string strResult2 = string.Empty;
                VisionPlatform.VisionManager.Engine eng = null;
                eng = new VisionPlatform.VisionManager.Engine(FileName);
                eng.SetInputNumber("PanNum", Convert.ToInt16(inputFixtureID));
                eng.SetInputString("ID", ID_SN);
                eng.SetInputNumber("isCutting", Iscutting);
                for (int i = 0; i < inputImageName.Count; i++)
                    eng.SetInputImage(inputImageName[i], InputImage[i]);
                eng.ActionFun();
                strResult = eng.GetOutputString(outDataName);
                strResult1 = eng.GetOutputString(outDataName1);
                strResult2 = eng.GetOutputString(outDataName2);
                if (strResult != "")
                {
                    Dictionary<string, double> dic = new Dictionary<string, double>();
                    dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);
                    int position = 0;

                    foreach (var item in dic)
                    {
                        string FAIName = item.Key;
                        string FAIValue = item.Value.ToString();
                        DataItem FAI = new DataItem
                        {
                            Name = FAIName,
                            Value = double.Parse(FAIValue),
                            Position = position
                        };
                        listDataItems.Add(FAI);
                    }
                }
                if (strResult1 != "")
                {
                    Dictionary<string, double> dic = new Dictionary<string, double>();
                    dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult1);
                    int position = 0;

                    foreach (var item in dic)
                    {
                        string FAIName = item.Key;
                        string FAIValue = item.Value.ToString();
                        DataItem FAI = new DataItem
                        {
                            Name = FAIName,
                            Value = double.Parse(FAIValue),
                            Position = position
                        };
                        listDataItems1.Add(FAI);
                    }
                }
                if (strResult2 != "")
                {
                    Dictionary<string, double> dic = new Dictionary<string, double>();
                    dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult2);
                    int position = 0;

                    foreach (var item in dic)
                    {
                        string FAIName = item.Key;
                        string FAIValue = item.Value.ToString();
                        DataItem FAI = new DataItem
                        {
                            Name = FAIName,
                            Value = double.Parse(FAIValue),
                            Position = position
                        };
                        listDataItems2.Add(FAI);
                    }
                }
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName} 算法处理报错:{ex}", LogType.Error);
                return false;
            }

            return true;
        }

        public class ImageRefreshEventArgs : EventArgs
        {
            public string SN;
            public List<string> Imagesname;
            public List<HImage> Images;
            public string panNum;
        }
    }
}
